<?php

namespace App\Models;

// use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Support\Facades\Hash;

class User extends Authenticatable
{
  use HasApiTokens, HasFactory, Notifiable;

  /**
   * Insert validation rules.
   */
  public static $insertRules = [
    'name' => 'required|max:255',
    'email' => 'required|email|max:255|unique:users',
    'password' => 'required|min:8|max:255',
  ];

  /**
   * Update validation rules.
   */
  public static $updatetRules = [
    'name' => 'nullable|max:255',
  ];

  /**
   * Login validation rules.
   */
  public static $loginRules = [
    'email' => 'required|email',
    'password' => 'required',
  ];

  /**
   * The attributes that are mass assignable.
   */
  protected $fillable = [
    'name',
    'email',
    'password',
    'active',
    'registered',
    'email_verified_at',
    'role_id'
  ];

  /**
   * The attributes that should be hidden for serialization.
   */
  protected $hidden = [
    'password',
    'remember_token',
    'role_id'
  ];

  /**
   * The attributes that should be cast.
   */
  protected $casts = [
    'email_verified_at' => 'datetime',
    'last_login_at' => 'datetime',
    'last_logout_at' => 'datetime',
  ];

  /**
   * setPasswordAttribute.
   *
   * Mutator to encrypt password
   */
  public function setPasswordAttribute($password)
  {
    $this->attributes['password'] = Hash::make($password);
  }

  /**
   * Relationship with role.
   */
  public function role()
  {
    return $this->belongsTo(Role::class);
  }

  /**
   * Relationship with person.
   */
  public function person()
  {
    return $this->hasOne(Person::class);
  }

  /**
   * Relationship with company.
   */
  public function company()
  {
    return $this->hasOne(Company::class);
  }

  /**
   * Relationship with picture.
   */
  public function picture()
  {
    return $this->hasOne(Picture::class);
  }

  /**
   * Relationship with address.
   */
  public function addresses()
  {
    return $this->hasMany(Address::class);
  }

  /**
   * Relationship with telephones.
   */
  public function telephones()
  {
    return $this->hasMany(Telephone::class);
  }

  /**
   * Relationship with emails.
   */
  public function emails()
  {
    return $this->hasMany(Email::class);
  }

  public function hasPermissionThroughRole($permission)
  {
    $result = false;
    foreach ($this->role->permissions as $perm) {
      if ($perm->slug == $permission) {
        $result = true;
      }
    }
    return $result;
  }
}
